package com.github.manx98.okdownloader.utils;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Response;

import java.util.List;
import java.util.Objects;

import com.github.manx98.okdownloader.exception.GetFileSizeFailException;

/**
 * 下载链接检查工具
 *
 * @author : manx98
 * @date : 2021/5/24
 */
public class LinkCheckUtil {

    private LinkCheckUtil() {
    }

    /**
     * 解析链接指向的文件大小
     *
     * @param links  链接
     * @param client OkHttpClient
     * @return 文件大小
     */
    public static long getFileSize(List<DownloadLink> links, OkHttpClient client) throws GetFileSizeFailException {
        for (DownloadLink link : links) {
            final Call call = client.newCall(link.getDownloadRequest());
            try (Response response = call.execute()) {
                if (response.isSuccessful()) {
                    return Long.parseLong(Objects.requireNonNull(response.header("Content-Length")));
                }
            } catch (Exception e) {
                throw new GetFileSizeFailException("解析文件大小出错:" + e.getMessage());
            }
        }
        throw new GetFileSizeFailException("无法解析文件大小");
    }
}
